
# Embedded file name: commu\comm_serial.py
import serial, re, time, logging

from xmodem import XMODEM


class CommSerial:
    def __init__(self, port, baudrate):
        self.com_output = None
        self.serial = None
        self.serial = serial.Serial(port, baudrate)

    def isOpen(self):
        return self.serial.isOpen()
    
    def open(self, port, baudrate):
        self.serial.port = port
        self.serial.baudrate = baudrate
        try:
            self.serial.open()
        except:
            print("串口异常", "串口打开失败！错误：拒绝访问（被占用）.")
            return None

    def read_all(self) -> str:
        data = self.serial.read(self.serial.in_waiting).decode("utf-8", "ignore")
        return data

    def read_line(self, timeout=1.0) -> str:
        time_limit = time.time() + timeout
        line = ""
        while time.time() < time_limit:
            while self.serial.in_waiting > 0:
                char = self.serial.read(1).decode("utf-8", "ignore")
                line += char
                if char == "\n":
                    return line

        return ""

    def send_cmd(self, cmd, match=None, confirm=False, timeout=10.0):
        data = ""
        success_keyword = ""
        if confirm:
            data = cmd + " ;" + 'CMDRET=$?;if [ "$CMDRET" -eq "0" ];then result="Successful";' + 'else result="Failure";fi;for i in `seq 10`;' + "do echo __Command__Result:$result;done\n"
            success_keyword = "__Command__Result:Successful\r\n"
        else:
            data = cmd + "\n"
        self.serial.read(self.serial.in_waiting)
        self.serial.write(data.encode(encoding="utf-8", errors="strict"))
        is_match = True if match is None else False
        is_confirm = True if confirm is False else False
        time_limit = time.time() + timeout

        while time.time() < time_limit:
            if is_match:
                if is_confirm:
                    return True
            line = self.read_line(timeout=(time_limit - time.time()))
            if not is_match:
                is_match = True if match in line else False
            else:
                is_confirm = is_confirm or (True if success_keyword in line else False)

        return False
    
    def read(self, size):
        if self.serial.in_waiting >= size:
            gbytes = self.serial.read(size)
            return gbytes
        else:
            return None
        #return gbytes or None

    def write(self, data):
        pbytes = self.serial.write(data)
        self.serial.flush()
        return pbytes or None
    def close(self):
        return self.serial.close()
    
if __name__ == "__main__":
    m_serial = CommSerial("/dev/ttyUSB0", 115200)
    ret = m_serial.send_cmd(cmd="G", match="",
      confirm=True)
    print(ret)

# okay decompiling E:\Pythontest\FactoryTestTool.exe_extracted\PYZ-00.pyz_extracted\commu.my_serial.pyc
